package Test09;

//反射

/*
Class类中用于获取成员变量的方法
    Field[] getFields():返回所有公共成员变量对象的数组
    Field[] getDeclaredFields():返回所有成员变量对象的数组
    Field getField(String name):返回单个公共成员变量对象
    Field getDeclaredField(Stringname):返回单个成员变量对象

Field类中用于创建对象的方法
    void set(Object obj, Object value): 赋值
    Object get(Object obj) 获取值
 */

import java.lang.reflect.Field;

public class Test03 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {

        //1、获取class字节码文件
        Class clazz = Class.forName("Test09.Student03");

        /*//2、获取所有的成员变量
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            System.out.println(field);
        }*/

        //3、获取单个的成员变量
        /*Field gender = clazz.getField("gender");
        System.out.println(gender);*/
        Field name = clazz.getDeclaredField("name");
        System.out.println(name);

        //获取权限修饰符
        int modifiers = name.getModifiers();
        System.out.println(modifiers);

        //获取成员变量的名字
        String n = name.getName();
        System.out.println(n);

        //获取成员变量的类型
        Class<?> type = name.getType();
        System.out.println(type);

        //获取成员变量的值
        Student03 stu = new Student03("zhangsan", 23, "男");
        name.setAccessible(true);
        String value = (String) name.get(stu);
        System.out.println(value);
        System.out.println(stu);

        //修改对象里面的值
        name.set(stu, "lisi");

        System.out.println(stu);
    }
}

class Student03 {

    private String name;
    private int age;
    public String gender;

    public Student03() {
    }

    public Student03(String name, int age, String gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    /**
     * 获取
     *
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     *
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取
     *
     * @return age
     */
    public int getAge() {
        return age;
    }

    /**
     * 设置
     *
     * @param age
     */
    public void setAge(int age) {
        this.age = age;
    }

    /**
     * 获取
     *
     * @return gender
     */
    public String getGender() {
        return gender;
    }

    /**
     * 设置
     *
     * @param gender
     */
    public void setGender(String gender) {
        this.gender = gender;
    }

    public String toString() {
        return "Student03{name = " + name + ", age = " + age + ", gender = " + gender + "}";
    }
}
